package com.cy.system.shiro;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.cy.system.entity.Account;
import com.cy.system.entity.User;
import com.cy.system.service.UserService;

/**
 * 重写我们的登陆身份认证返回方法 类描述： 类名称：com.tz.ssspm.security.LoginFormAuthticationFilter
 * 创建人：tz 创建时间：2016年11月19日 下午10:24:53
 * 
 * @version V1.0
 */
public class MyFormAuthenticationFilter extends FormAuthenticationFilter {
	private final static Logger logger = Logger.getLogger(MyFormAuthenticationFilter.class);
	
	@Autowired
	private UserService userService;
	/**
	 * 重写身份认证不成功方法
	 */
	/*
	 * protected boolean onLoginFailure(AuthenticationToken token,
	 * AuthenticationException e, ServletRequest request, ServletResponse response){
	 * String errorMsg = ""; if(e instanceof UnknownAccountException || e instanceof
	 * IncorrectCredentialsException){ errorMsg = "用户名和密码不正确";
	 * 
	 * }else{ errorMsg = "出现未知错误,请联系管理员"; } request.setAttribute("errorMsg",
	 * errorMsg);
	 * 
	 * return true; }
	 */

	/**
	 * 重写登录成功方法
	 */
	@Override
	protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,
			ServletResponse response) throws Exception {
		// 获取已登录的用户信息
		Account account = (Account) subject.getPrincipal();
		// 获取session
		HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
		HttpSession session = httpServletRequest.getSession();
		// 把用户信息保存到session
		User user = userService.getUserByAccountId(account.getAccountId());
		session.setAttribute("userSession", user);
		/* issueSuccessRedirect(request, response); */
		logger.info("==> 登录成功！存入userSession["+session.getAttribute("userSession")+"]");
		return super.onLoginSuccess(token, subject, request, response);
	}

	/**
	 * 重写身份认证成功以后返回地址
	 */
	@Override
	protected void issueSuccessRedirect(ServletRequest request, ServletResponse response) throws Exception {
		String successUrl = getSuccessUrl();
		logger.info("==> 返回主页成功！返回successUrl:["+successUrl+"]");		
		WebUtils.issueRedirect(request, response, successUrl, null, true);
	}

}
